package com.zhl.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.zhl.mapper.UserMapper;
import com.zhl.model.User;
@Service
public class UserService {

	@Autowired
	UserMapper usermapper;

	//使用一个叫userCache的缓存
	@Cacheable(value="userCache")
	public User getUserByName(String name){
		//不用考录缓存逻辑
		
		return getFromDB(name);
	}
/*	@Cacheable(value="userCache")
	public User getUserByName2(String name) { 
		return this.getUserByName(name); 
	} */

	
	private User getFromDB(String name){
		System.out.println("执行这个方法，说明缓存中没有数据："+name);
		System.out.println("数据库获得数据："+name);
		return usermapper.findByName(name);
	}

	@CachePut(value="userCache",key="#user.getName()")
	// 清空 userCache 缓存, Key 是用来指定缓存的 key 的
	public void update(User user) {
		System.out.println("更新");
		updateDB(user); 
	} 

	@CacheEvict(value="userCache",allEntries=true,beforeInvocation=true)
	// 清空 userCache 缓存,清空所有
	public void reload() { 
		   
	} 

	@Cacheable(value="userCache")
	public List<User> getAll() { 
		System.out.println("从数据库查询");
		return usermapper.findAll();
	} 
	
	private void updateDB(User user) { 
		usermapper.update(user);
		System.out.println("更新数据："+user.getName()); 
	} 
	
	
}
